/*
 * Software for Interactive Project Pool Game
 * Columbia University. New York, 2008
 * Authors:
 *   Abdulhamid Ghandour
 *   Thomas John
 *   Jaime Peretzman
 *   Bharadwaj Vellore
 * 
 * Desc:
 */
#include "fixedpoint.h"
#include "debug.h"

/*
// Thanks to GameProgrammer.com
*/
#define step(shift) \
    if((0x40000000l >> shift) + root <= num)          \
    {                                                   \
        num -= (0x40000000l >> shift) + root;         \
        root = (root >> 1) | (0x40000000l >> shift);    \
    }                                                   \
    else                                                \
    {                                                   \
        root = root >> 1;                               \
    }

long long FPSQRT(long long num){
    long long root = 0;

    step( 0);
    step( 2);
    step( 4);
    step( 6);
    step( 8);
    step(10);
    step(12);
    step(14);
    step(16);
    step(18);
    step(20);
    step(22);
    step(24);
    step(26);
    step(28);
    step(30);

    // round to the nearest integer, cuts max error in half

    if(root < num)
    {
        ++root;
    }

    root <<= 6;

    return root;
}
/*
long long FPSQRT(long long num){
  long long next, root;

  if(num < INT2FP(1LL)){
    root = 0;
  }else{
    next = num >> 2;
    do{
      root = next;
      next = (next + FPDIV(num,next)) >> 1;
    }while(root != next);
  }
 
  return root;
}*/

void printFP(long long fpnum){
  int i;
  float factor = 0.5;
  float result = 0;
  for(i=FRAC_PRECISION - 1; i >= 0; i--){
    if(fpnum & (0x1 << i)){
      result += factor;
    }
    factor *= 0.5;
  }
  printf("%.4f\n",result + FP2INT(fpnum));    
}
